/**
 * 十六进制转rgb
 * @param {*} color 例如：#cccccc
 * @returns rgb(0,0,0)
 */
const hexToRgb = (color) => {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  color = color.replace(shorthandRegex, function (m, r, g, b) {
    return r + r + g + g + b + b;
  });

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : {
        r: 0,
        g: 0,
        b: 0,
      };
};


/**
 * 创建一个临时图片
 * @param {*} source 可以是路径（包括svg路径）、base64、svg代码
 * @param {} isSvg 是否是svg代码
 * @returns 
 */
const createImage = ({source, isSvg = false}) => {
  const pro = new Promise((resolve, reject) => {
    const imgElement = new Image();
    if (isSvg) {
      imgElement.src =
        "data:image/svg+xml," + unescape(encodeURIComponent(source)); //svg内容中可以有中文字符
      // imgElement.src = "data:image/svg+xml," + svg2; //svg内容中不能有中文字符
    } else {
      imgElement.src = source;
    }
    imgElement.onload = () => {
      resolve(imgElement);
    };
  });
  return pro;
};


/**
 * svg转换为指定颜色，并返回base64
 * @param {*} source svg代码
 * @param {*} color 颜色
 * @returns 
 */
const svgSetColorToBase64 = async ({source, color = "#888"}) => {
  const imgElement = await createImage({ source, isSvg: true });
  const pro = new Promise((resolve, reject) => {
    const canvas = document.createElement("canvas");
    canvas.width = imgElement.width;
    canvas.height = imgElement.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(imgElement, 0, 0, canvas.width, canvas.height);
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    const rgbColor = hexToRgb(color);
    for (let p = 0, len = data.length; p < len; p += 4) {
      if (data[p + 3] == 0) continue;
      data[p + 0] = rgbColor.r;
      data[p + 1] = rgbColor.g;
      data[p + 2] = rgbColor.b;
      data[p + 3] = 255;
    }
    ctx.putImageData(imageData, 0, 0);
    resolve(canvas.toDataURL());
  });
  return pro;
};

/**
 * 在canvas中，将svg转换为指定大小，指定颜色的canvas
 * @param {*} source svg代码
 * @param {*} color 颜色
 * @param {} cw canvas的宽
 * @param {} ch canvas的高
 * @param {} iw canvas里图片的宽 （一般不能大于canvas的宽， 设小之后作为图片循环的间距）
 * @param {} ih canvas里图片的高 （一般不能大于canvas的高， 设小之后作为图片循环的间距）
 * @returns 
 */

const svgSetColor = ({source, color = "#888", cw = 20, ch = 20, iw, ih}) => {
  iw = iw || cw;
  ih = ih || ch;
  const pro = new Promise((resolve, reject) => {
    let tempCanvas = document.createElement("canvas");
    tempCanvas.width = cw;
    tempCanvas.height = ch;
    let tempCtx = tempCanvas.getContext("2d");
    svgSetColorToBase64({ source, isSvg: true, color }).then((res) => {
      createImage({ source: res }).then((res2) => {
        tempCtx.drawImage(res2, 0, 0, iw, ih);
        resolve(tempCanvas);
      });
    });
  });
  return pro;
};

export default { hexToRgb, createImage, svgSetColor, svgSetColorToBase64 };
